<template>
    <div class="login">
      <div class="box">
        <h2>智慧医疗</h2>
        <div class="scanner-container">
          <div v-show="!isLoading">
            <video poster="data:image/gif,AAAA" ref="scanner"></video>
            <div class="overlay-element" :style="overlayStyle"></div>
            <div class="laser" :style="laserStyle"></div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import { BrowserMultiFormatReader, BarcodeFormat } from "@zxing/library";
  
  export default {
    name: "Login",
  
    data() {
      return {
        isLoading: true,
        codeReader: new BrowserMultiFormatReader(),
        isMediaStreamAPISupported: navigator && navigator.mediaDevices && "enumerateDevices" in navigator.mediaDevices,
        selectedDeviceId: null, // 存储选中的设备ID
        cameraName: 'USB2.0 Camera RGB', // 提取摄像头名称
        overlayStyle: {
          top: '20%',
          left: '10%',
          width: '80%',
          height: '40%',
        },
        laserStyle: {
          top: '30%',
          left: '20%',
          width: '60%',
        },
      };
    },
  
    mounted() {
      console.log("Component mounted");
  
      if (!this.isMediaStreamAPISupported) {
        console.error("Media Stream API is not supported");
        throw new Error("Media Stream API is not supported");
      }
  
      this.selectCamera().then(() => {
        this.start();
        this.$refs.scanner.oncanplay = (event) => {
          console.log("Video can play, setting isLoading to false");
          this.isLoading = false;
          this.$emit("loaded");
        };
      });
    },
  
    beforeUnmount() {
      console.log("Component about to unmount, resetting code reader");
      this.codeReader.reset();
    },
  
    methods: {
      async selectCamera() {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const videoDevices = devices.filter(device => device.kind === 'videoinput');
  
        for (const device of videoDevices) {
          if (device.label.includes(this.cameraName) || device.deviceId.includes(this.cameraName)) {
            this.selectedDeviceId = device.deviceId;
            break;
          }
        }
  
        if (!this.selectedDeviceId) {
          console.warn(`No ${this.cameraName} camera found, using the first available camera.`);
          this.selectedDeviceId = videoDevices.length > 0 ? videoDevices[0].deviceId : undefined;
        }
      },
  
      start() {
        console.log("Starting barcode/QR code scanning");
  
        this.codeReader.decodeFromVideoDevice(this.selectedDeviceId, this.$refs.scanner, (result, err) => {
          if (result) {
            console.log("Barcode/QR code decoded:", result.text);
            localStorage.setItem('caseNo', result.text); 
            this.$router.push({
              name: "Frame"
            });
            this.$emit("decode", result.text);
            this.$emit("result", result);
  
            // 动态调整扫描区域的位置
            this.adjustOverlay(result);
          }
        }, {
          formats: [BarcodeFormat.EAN_13, BarcodeFormat.CODE_128, BarcodeFormat.QR_CODE], // 支持的条形码格式
          tryHarder: true, // 更努力地尝试解码
          rotation: 0, // 不旋转视频流
        });
      },
  
      adjustOverlay(result) {
        const video = this.$refs.scanner;
        const videoWidth = video.videoWidth;
        const videoHeight = video.videoHeight;
  
        // 获取条形码或二维码的位置信息
        const points = result.resultPoints;
        if (points && points.length >= 4) {
          const [topLeft, topRight, bottomRight, bottomLeft] = points;
  
          // 计算新的扫描区域位置
          const x = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
          const y = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
          const width = Math.max(bottomRight.x, topRight.x, bottomLeft.x, topLeft.x) - x;
          const height = Math.max(bottomRight.y, topRight.y, bottomLeft.y, topLeft.y) - y;
  
          // 确保扫描区域在视频区域内
          const newTop = Math.max(0, (y / videoHeight) * 100);
          const newLeft = Math.max(0, (x / videoWidth) * 100);
          const newWidth = Math.min(100, (width / videoWidth) * 100);
          const newHeight = Math.min(100, (height / videoHeight) * 100);
  
          // 更新样式
          this.overlayStyle = {
            top: `${newTop}%`,
            left: `${newLeft}%`,
            width: `${newWidth}%`,
            height: `${newHeight}%`,
          };
  
          // 更新激光线的位置
          const laserTop = `${((y + height / 2) / videoHeight) * 100}%`;
          this.laserStyle = {
            top: laserTop,
            left: `${newLeft}%`,
            width: `${newWidth}%`,
          };
        }
      },
    },
  };
  </script>
  
  
  
  <style scoped>
  .login {
    width: 100%;
    height: 100%;
    background-image: url("../assets/image/login.jpg");
    position: fixed;
    background-size: cover;
  }
  
  .box {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 500px;
    height: 300px;
    margin: auto;
    border: 1px solid #ccc;
    background-color: rgba(255, 255, 255, 0.34);
  }
  
  .box h2 {
    padding: 20px 0 20px 0;
    font-size: 30px;
    font-weight: 900;
    text-align: center;
    line-height: 30px;
    color: #3333aa;
  }
  
  .el-form .el-form-item i {
    width: 50px;
    color: #3333aa;
  }
  
  .el-form .el-form-item .el-input {
    width: 250px;
  }
  
  .el-form .el-form-item .el-button {
    background-color: #3333aa;
    color: #fff;
    padding: 10px 30px;
    border: 1px solid #fff;
    cursor: pointer;
    font-size: 18px;
  }
  
  video {
    max-width: 100%;
    max-height: 100%;
  }
  
  .scanner-container {
    position: relative;
  }
  
  .overlay-element {
    position: absolute;
    background: rgba(30, 30, 30, 0.5);
    -webkit-clip-path: polygon(0% 0%, 0% 100%, 10% 100%, 10% 10%, 90% 10%, 90% 90%, 10% 90%, 10% 100%, 100% 100%, 100% 0%);
    clip-path: polygon(0% 0%, 0% 100%, 10% 100%, 10% 10%, 90% 10%, 90% 90%, 10% 90%, 10% 100%, 100% 100%, 100% 0%);
  }
  
  .laser {
    position: absolute;
    background-color: tomato;
    height: 1px;
    z-index: 2;
    box-shadow: 0 0 4px red;
    -webkit-animation: scanning 2s infinite;
    animation: scanning 2s infinite;
  }
  
  @-webkit-keyframes scanning {
    50% {
      -webkit-transform: translateY(75px);
      transform: translateY(75px);
    }
  }
  
  @keyframes scanning {
    50% {
      -webkit-transform: translateY(75px);
      transform: translateY(75px);
    }
  }
  </style>
